﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaProduct;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaProduct;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;
using YNTK.Common.Model.NPOI;
using YNTK.Common.Configuration;
using YNTK.DataEncryption;
using YNTK.ClayObject;
using YNTK.System.Interfaces.System;

namespace YNTK.SubDev.ZyOaProduct
{
    /// <summary>
    /// 产品管理服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev",Name = "ZyOaProduct", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaProductService : IZyOaProductService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaProductEntity> _zyOaProductRepository;
        private readonly IBillRullService _billRuleService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaProductService"/>类型的新实例
        /// </summary>
        public ZyOaProductService(
            ISqlSugarRepository<ZyOaProductEntity> zyOaProductRepository,
            IBillRullService billRuleService,
            IUserManager userManager)
        {
            _zyOaProductRepository = zyOaProductRepository;            
            _db = _zyOaProductRepository.Context;
            _billRuleService = billRuleService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取产品管理
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaProductEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaProductInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取产品管理列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ZyOaProductListQueryInput input)
        {
            var sidx = input.sidx == null ? "creatorTime" : input.sidx;
            var data = await _db.Queryable<ZyOaProductEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.name), p => p.Name.Contains(input.name))
                .WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
                .Select(it=> new 
                {
                    id = it.Id,
                    encode=it.Encode,
                    name=it.Name,
                    type=it.Type,
                    brand=it.Brand,
                    lowerPrice=it.LowerPrice,
                    proposedPrice=it.ProposedPrice,
                    submaxv=it.Submaxv,
                    subminv=it.Subminv,
                    unit=it.Unit,
                    creatorTime=it.CreatorTime,
                    creatorUserId=it.CreatorUserId,
                }).MergeTable().Select<ZyOaProductListOutput>().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return TkPageResult<ZyOaProductListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建产品管理
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaProductCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaProductEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.Encode = await _billRuleService.GetBillNumber("ZYCP");
            entity.CreatorTime = DateTime.Now;  
            entity.CreatorUserId = _userManager.UserId;
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
		/// 获取产品管理无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] ZyOaProductListQueryInput input)
        {
            var sidx = input.sidx == null ? "creatorTime" : input.sidx;
            var data = await _db.Queryable<ZyOaProductEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.name), p => p.Name.Contains(input.name))
                .WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
                .Select(it=> new 
                {
                    id = it.Id,
                    encode=it.Encode,
                    name=it.Name,
                    type=it.Type,
                    brand=it.Brand,
                    lowerPrice=it.LowerPrice,
                    proposedPrice=it.ProposedPrice,
                    submaxv=it.Submaxv,
                    subminv=it.Subminv,
                    unit=it.Unit,
                    creatorTime=it.CreatorTime,
                    creatorUserId=it.CreatorUserId,
                }).MergeTable().Select<ZyOaProductListOutput>().OrderBy(sidx+" "+input.sort).ToListAsync();
                return data;
        }

        /// <summary>
		/// 导出产品管理
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] ZyOaProductListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<ZyOaProductListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.GetList(input));
                exportData = data.Solidify<TkPageResult<ZyOaProductListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"产品编号\",\"field\":\"encode\"},{\"value\":\"产品名称\",\"field\":\"name\"},{\"value\":\"产品品牌\",\"field\":\"brand\"},{\"value\":\"产品类型\",\"field\":\"type\"},{\"value\":\"产品单位\",\"field\":\"unit\"},{\"value\":\"最低销售价\",\"field\":\"lowerPrice\"},{\"value\":\"市场参考价\",\"field\":\"proposedPrice\"},{\"value\":\"库存预警下限\",\"field\":\"subminv\"},{\"value\":\"库存预警上限\",\"field\":\"submaxv\"},{\"value\":\"创建用户\",\"field\":\"creatorUserId\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},]".ToList<ParamsModel>();           
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "产品管理.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<ZyOaProductListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "YNTK")
            };
            return output;
        }

        /// <summary>
        /// 批量删除产品管理
        /// </summary>
        /// <param name="ids">主键数组</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var entitys = await _db.Queryable<ZyOaProductEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    //开启事务
                    _db.Ado.BeginTran();
                    //批量删除产品管理
                    await _db.Deleteable<ZyOaProductEntity>().In(d => d.Id,ids).ExecuteCommandAsync();
                    //关闭事务
                    _db.Ado.CommitTran();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.Ado.RollbackTran();
                    throw YNTKException.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 更新产品管理
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaProductUpInput input)
        {
            var entity = input.Adapt<ZyOaProductEntity>();
            entity.LastModifyTime = DateTime.Now;  
            entity.LastModifyUserId = _userManager.UserId;
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除产品管理
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaProductEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyOaProductEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }
    }
}
